package cn.hs.controller;

import cn.hs.util.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName FileUploadController
 * @Description TODO
 * @Author yun
 * @Date 2024年10月23日 15:34
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
public class FileUploadController {

    private final String Path = "D:\\Program Files\\ideaProgram\\updateFiles";

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        if(file.isEmpty()){
            return Result.error("文件为空");
        }
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString().replace("-","")+"-"+fileName;
        try {
            file.transferTo(new File(Path,fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(fileName);
    }

    @GetMapping("/load")
    public Result load(String fileName, HttpServletResponse resp){

        if(fileName.isEmpty() || fileName.equals("null")){
            return Result.error();
        }

        File file = new File(Path,fileName);
        try (
                ServletOutputStream os = resp.getOutputStream();
                FileInputStream is = new FileInputStream(file)){

            resp.setHeader("Content-Disposition","filename="+fileName);
            IOUtils.copy(is,os);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

}
